package com.kefu.web.controller;

import com.kefu.common.JsonResult;
import com.kefu.common.redis.PubClient;
import com.kefu.common.redis.SubClient;
import com.kefu.model.Jurisdiction;
import com.kefu.model.Kefu;
import com.kefu.model.Msg;
import com.kefu.service.JurisdictionService;
import com.kefu.service.KefuService;
import com.kefu.common.redis.RedisMsgPubSubListener;
import com.kefu.service.PubClientService;
import com.sys.model.Role;
import com.sys.model.User;
import com.sys.service.RoleService;
import com.sys.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;

import org.slf4j.Logger;

/**
 * Created by Administrator on 2016/11/25.
 */
@SuppressWarnings("SpringJavaAutowiringInspection")
@RestController
@RequestMapping("/kefu")
public class KefuController {
    @Autowired
    private KefuService kefuService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserService userService;
    @Autowired
    private JurisdictionService jurisdictionService;
    @Autowired
    private PubClientService pubClientService;

    private static Logger log= org.slf4j.LoggerFactory.getLogger(KefuController.class);

    //返回医生列表
    @ApiOperation(value="返回医生列表", notes="返回医生列表")
    @RequestMapping(value = "/doctor",method = RequestMethod.GET)
    public JsonResult getDoc(){
        Role role= roleService.selectByName("看诊医生");
        List<User> doctors=userService.selectUsersByRoleId(role.getId());
        return new JsonResult("200","",doctors);
    }

    //登录处理
    @ApiOperation(value="登录处理", notes="登录处理")
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public JsonResult login(@RequestParam("username") String username,
                            @RequestParam("password") String password){
            try{
                Kefu kefu=kefuService.selectByNameAndPassword(username,password);
                return new JsonResult("200","登录成功！",kefu);
            }catch (Exception e){
                return new JsonResult("500",e.getMessage());
            }
    }

    //注册处理

    /**
     *
     * @param username
     * @param password
     * @param fullname
     * @param docId
     * @return
     */
    @ApiOperation(value="注册处理", notes="注册处理")
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public JsonResult register(@RequestParam("username") String username,
                               @RequestParam("password") String password,
                               @RequestParam("fullname") String fullname,
                               @RequestParam("docId") String docId){
        Kefu kefu=new Kefu();
        kefu.setId(UUID.randomUUID().toString());
        kefu.setUsername(username);
        kefu.setPassword(password);
        kefu.setFullname(fullname);
        kefu.setDocId(docId);
        try{
            kefuService.addKefu(kefu);
            return new JsonResult("200","注册成功",kefu);
        }catch (Exception e){
            return new JsonResult("500",e.getMessage());
        }
    }
    //编辑客服信息
    /**
     *
     * @param id
     * @param uusername
     * @param password
     * @param fullname
     * @param docId
     * @param jurisdictionIds
     * @return
     */
    @ApiOperation(value="编辑客服信息", notes="编辑客服信息")
    @RequestMapping(value = "/updatekefu/{id}",method = RequestMethod.POST)
    public JsonResult updateKefu(@PathVariable String id,@RequestParam("username")String uusername,
                                   @RequestParam("password")String password,@RequestParam("fullname")String fullname,
                                   @RequestParam("docId")String docId,@RequestParam("jurisdictionIds")List jurisdictionIds ){
        Kefu kefu=kefuService.findById(id);
        kefu.setUsername(uusername);
        kefu.setPassword(password);
        kefu.setFullname(fullname);
        kefu.setDocId(docId);
        kefu.setJurisdictionIds(jurisdictionIds);
        kefuService.updateById(kefu);
        return new JsonResult("200","",kefu);
    }


    //根据docId的消息发布到相关频道
    @ApiOperation(value="根据docId的消息发布到相关频道", notes="根据docId的消息发布到相关频道")
    @RequestMapping(value = "/pub",method = RequestMethod.POST)
    public JsonResult pub(@RequestParam("docId") String docId) {
        //具体逻辑看msg_pub的方法实现
        try{
            String a=pubClientService.msg_pub(docId);
            return new JsonResult("200","",a);
        }catch (Exception e){
            return new JsonResult("500",e.getMessage());
        }
    }

    //处理携带msg与docId的信息
    //此处理方法操作成功后，返回此医生id和绑定的客服id和这条msg信息内容。
    @ApiOperation(value="处理携带msg与docId的信息", notes="返回此医生绑定的客服id和这条msg信息内容")
    @RequestMapping(value = "/handlemsg",method = RequestMethod.POST)
    public JsonResult handleMsg(@RequestParam("docId") String docId,
                                @RequestParam("msg") String msg){
        try{
            Msg msg1=new Msg();
            msg1.setKefuId(kefuService.findByDocId(docId).getId());
            msg1.setMsg(msg);
            msg1.setDocId(docId);
            return new JsonResult("200","",msg1);
        }catch (Exception e){
            return new JsonResult("500",e.getMessage());
        }
    }

    //获取jurisdiction表的list
    @ApiOperation(value="获取jurisdiction表的list", notes="获取jurisdiction表的list")
    @RequestMapping(value = "/getjur",method = RequestMethod.POST)
    public JsonResult getJurisdiction(){
        List<Jurisdiction> jurisdictions= jurisdictionService.selectAll();
        return new JsonResult("200","",jurisdictions);
    }

    //编辑jurisdiction对象
    @ApiOperation(value="编辑jurisdiction对象", notes="编辑jurisdiction对象")
    @RequestMapping(value = "/updatejur/{id}",method = RequestMethod.POST)
    public JsonResult patch(@PathVariable int id,@RequestParam("fullname")String fullname ,
                            @RequestParam("parentId")String parentId){
        Jurisdiction jurisdiction=jurisdictionService.findById(id);
        jurisdiction.setFullName(fullname);
        jurisdiction.setParentId(parentId);
        jurisdiction.setDeleted(false);
        return new JsonResult("200","",null);
    }


    //测试类（可删除。。）
    @RequestMapping(value = "/test")
    public String a(){
        final RedisMsgPubSubListener pubsub = new RedisMsgPubSubListener();
//        JedisUtils.subscribeMsg(pubsub, "firsttest");
        new Thread(new Runnable() {
            public void run() {
                try{
                    //线程进入订阅模式，阻塞
                    SubClient.subscribeMsg(pubsub, "firsttest");
                    //当unsubscribe 方法被调用时，才执行以下代码
                    log.info("线程测试，取消订阅才能看到此信息。");
                } catch(Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
        return "看到我就成功了。";
    }
}
